package com.pangolin.pangolinim.ui.activity;

import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lqr.optionitemview.OptionItemView;
import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.R;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.net.NetFormat;
import com.pangolin.pangolinim.ui.adapter.UIContact;
import com.pangolin.pangolinim.ui.base.BaseActivity;
import com.pangolin.pangolinim.ui.fragment.ContactsFragment;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.GsonUtil;
import com.pangolin.pangolinim.utils.ImageUtil;
import com.pangolin.pangolinim.utils.SPUtil;
import com.pangolin.pangolinim.utils.UIUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserInfoActivity extends BaseActivity {
    private UIContact contact;
    private UIContact me;

    private TextView tvName;
    private ImageView ivHeader;
    private TextView tvUid;
    private Button btnChat;
    private ImageButton mIbToolbarMore;
    private RelativeLayout mRlMenu;
    private ScrollView mSvMenu;
    private OptionItemView mOivDelete;
    private Button btnAdd;

    private boolean isFriend;
    private boolean isFirstRun;

    @Override
    protected void init(){
        isFirstRun = true;

        String strMe = getIntent().getStringExtra("param1");
        String strContact = getIntent().getStringExtra("param2");
        if(strContact != null && strMe != null){
            me = GsonUtil.fromJson(strMe , UIContact.class);
            contact = GsonUtil.fromJson(strContact , UIContact.class);
//            Logger.d("me:%d|%s\ncontact:%d|%s" ,me.getUid() , me.getName() , contact.getUid() , contact.getName());
        }

        //判断是添加联系人还是已经是好友关系
        List<UIContact> mContacts = ContactsFragment.mContacts;
        isFriend = false;
        for(UIContact item : mContacts){
            if(contact.getUid() == item.getUid()){
                isFriend = true;
            }
        }
    }

    @Override
    protected void initView(){
        setToolbarTitle("");
        tvName = findViewById(R.id.tvName);
        ivHeader = findViewById(R.id.ivHeader);
        tvUid = findViewById(R.id.tvUid);
        btnChat = findViewById(R.id.btnCheat);
        mIbToolbarMore = findViewById(R.id.ibToolbarMore);
        mRlMenu = findViewById(R.id.rlMenu);
        mSvMenu = findViewById(R.id.svMenu);
        mOivDelete = findViewById(R.id.oivDelete);
        btnAdd = findViewById(R.id.btnAddToContact);

        mIbToolbarMore.setVisibility(View.VISIBLE);
        tvName.setText(contact.getName());
        tvUid.setText(String.valueOf(contact.getUid()));
        if(contact.getBitHeader() != null){
            ivHeader.setImageBitmap(contact.getBitHeader());
        }

        if(isFriend == false){
            btnChat.setVisibility(View.GONE);
            btnAdd.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        /** 检查头像图片，如果没有就开启异步下载 , 该操作只在初始化时执行一次 */
        if(isFirstRun && TextUtils.isEmpty(contact.getHeader()) == false && contact.getBitHeader() == null){
            /** 通知服务下载头像图片 */
            Map<String, Object> brocastMap = new HashMap<String, Object>();
            brocastMap.put("type" , BroadcastMsg.DATA_UI_DOWNPIC);
            brocastMap.put("uid" , contact.getUid());
            brocastMap.put("filename" , contact.getHeader());
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
            BroadcastSender(bundleUtil.getBundle());
            isFirstRun = false;
        }
    }

    @Override
    protected void initListener(){
        btnChat.setOnClickListener(v -> {
            jumpToActivity(SessionActivity.class , GsonUtil.toJson(me) , GsonUtil.toJson(contact));
            finish();
        });
        btnAdd.setOnClickListener(v -> {
            //添加好友请求
            Map<String, Object> brocastMap = new HashMap<String, Object>();
            brocastMap.put("type" , BroadcastMsg.DATA_UI_OPERATE);
            brocastMap.put("uid" , contact.getUid());
            brocastMap.put("name" , contact.getName());
            brocastMap.put("headimg" , contact.getHeader());
            brocastMap.put("context" , "hello");
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
            BroadcastSender(bundleUtil.getBundle());
        });

        mIbToolbarMore.setOnClickListener(v -> showMenu());
        mRlMenu.setOnClickListener(v -> hideMenu());
        mOivDelete.setOnClickListener(v -> {
            hideMenu();
            //删除联系人
            showMaterialDialog(UIUtil.getString(R.string.delete_contact),
                    UIUtil.getString(R.string.delete_contact_content, contact.getName()),
                    UIUtil.getString(R.string.delete),
                    UIUtil.getString(R.string.cancel),
                    v1 -> {
                            hideMaterialDialog();
                            deleteContact(contact.getUid());
                        },
                    v2 -> hideMaterialDialog());
        });
    }

    @Override
    protected void CoreMessage(BundleUtil bundleUtil){
        if(bundleUtil.getType() == BroadcastMsg.SIG_CORE_DATA){
            if(bundleUtil.getData() != null){
                Map<String, Object> resMap = bundleUtil.getData();
                Logger.d(resMap);
                if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_DOWNPIC){
                    if((int)resMap.get("result") == 0){
                        Logger.d("头像下载完毕"+(String)resMap.get("filename"));
                        File file = new File(getExternalFilesDir(String.valueOf(me.getUid())) , (String)resMap.get("filename"));
                        if(file.exists() && file.isFile()){
                            contact.setBitHeader(ImageUtil.getBitmapFromFile(this , file , 120 , 120));
                            ivHeader.setImageBitmap(contact.getBitHeader());
                        }else{
                            UIUtil.showToast("头像图片文件丢失，请重新下载");
                        }
                    }else{
                        UIUtil.showToast((String) resMap.get("msg"));
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_DELETE){
                    if((int)resMap.get("result") == 0){
                        UIUtil.showToast("联系人删除成功");
                        //更新联系人列表
                        finish();
                    }else{
                        UIUtil.showToast((String) resMap.get("msg"));
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_OPERATE){
                    if((int)resMap.get("result") == 0){
                        UIUtil.showToast("已发送好友申请，等待对方接受");
                    }else{
                        UIUtil.showToast((String) resMap.get("msg"));
                    }
                }
            }
        }
    }

    @Override
    protected int provideContentViewId(){
        return R.layout.activity_user_info;
    }

    private void showMenu() {
        mRlMenu.setVisibility(View.VISIBLE);
        TranslateAnimation ta = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
        ta.setDuration(200);
        mSvMenu.startAnimation(ta);
    }

    private void hideMenu() {
        TranslateAnimation ta = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
        ta.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mRlMenu.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ta.setDuration(200);
        mSvMenu.startAnimation(ta);
    }

    /**
     * TODO:发送删除好友请求
     * @param uid 好友uid
     */
    private void deleteContact(int uid){
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_DELETE);
        brocastMap.put("uid" , uid);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        BroadcastSender(bundleUtil.getBundle());
    }
}